package xyz.yuanjilu.service.impl;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.kit.MongoQuery;
import com.mongodb.MongoClient;

import xyz.yuanjilu.service.BaseMongoDao;



/**
 * 
 * https://github.com/T-baby/MongoDB-Plugin
 */
@Component
@WebListener
public class BaseMongoDaoImpl implements BaseMongoDao ,ServletContextListener{
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	/**
	 * 
	 * @param database 数据库名
	 * @param use 集合名
	 * @param obj 数据
	 */
	public String save(String use,Object obj) {
	
		MongoQuery query = new MongoQuery();
		query.use(use).set(obj).save();
		return query.getId();
	}
	
	@Override
	/**
	 * 
	 * @param database 数据库名
	 * @param use 集合名
	 * @param obj 数据
	 */
	public MongoQuery query(String use) {
		//mongoPlugin.setDatabase(database);
		
		//MongoClient mongoClient=initMongoClient();
		MongoQuery query = new MongoQuery();
		
		return query.use(use);
	}

	

	@Override
	public void close() {
		MongoClient client = MongoKit.INSTANCE.getClient();
		if (client!=null) {
			//client.close();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		MongoClient client = MongoKit.INSTANCE.getClient();
		if (client!=null) {
			client.close();
		}
		/*logger.info("容器销毁开始关闭活动的mongo链接");
		Collection<MongoKit> values = MongoKit.MongoKits.values();
		for (MongoKit mongoKit : values) {
			MongoClient client = mongoKit.getClient();
			if (client!=null) {
				logger.info("关闭链接{}",client.toString());
				client.close();
			}
		}*/
		
	}
	
	

}